package com.ougy.reshop.test.recognition;

import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

public abstract class JsonResultRecognition<T> extends
		ResultRecognition<T, JSONObject> {

	public abstract T childRecognition(JSONObject obj) throws Exception;

	protected int getTotalSize(JSONObject obj) throws JSONException {
		return obj.getInt("num");
	}

	protected boolean getBoolean(JSONObject obj, String name) {
		try {
			return obj.getBoolean(name);
		} catch (Exception e) {
			return false;
		}
	}

	protected double getDouble(JSONObject obj, String name) {
		try {
			return obj.getDouble(name);
		} catch (Exception e) {
			return 0;
		}
	}

	protected int getInt(JSONObject obj, String name) {
		try {
			return obj.getInt(name);
		} catch (Exception e) {
			return 0;
		}
	}

	protected long getLong(JSONObject obj, String name) {
		try {
			return obj.getLong(name);
		} catch (Exception e) {
			return 0;
		}
	}

	protected String getString(JSONObject obj, String name) {
		try {
			return obj.getString(name);
		} catch (Exception e) {
			return null;
		}
	}

	public T recognition(String result) {
		try {
			JSONTokener jsonTokener = new JSONTokener(result);
			JSONObject obj = (JSONObject) jsonTokener.nextValue();
			boolean hasData = obj.has("data");
			if (!hasData) {
				return null;
			}
			return childRecognition(obj.getJSONObject("data"));
		} catch (Exception e) {
			throw new RuntimeException("json parse error" + e);
		}
	}
}
